/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Parser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Nicolás Loaiza Cardona (nicoloaiza@gmail.com)
 */
public class Parser {
    
    /**
    * Constructor
    * @param  base  string to parse
    * @param  header  header indicating the fields in the line
    * @param  delimiter delimiter for the csv file.
    * @return  HashMap  with the pairs header - data
    */      
    public static HashMap Parse(String base,ArrayList<String> header,String delimiter)
    {
        ArrayList<String> strings = new ArrayList<String>();
        Pattern pattern = Pattern.compile("(?:^|" + delimiter + ")(\"(?:[^\"]|\"\")*\"|[^" + delimiter + "]*)");
        if(base.endsWith(delimiter))
            base = base.substring(0, base.length() - 1);
        Matcher matcher = pattern.matcher(base);
        while (matcher.find()) { 
                strings.add(matcher.group().replace(",", "").trim());
        }    
        HashMap table = null;
        if((strings.size() <= header.size()))
        {
            table = new HashMap();
            int counter= 0;
            for(String cad : strings)
            {
                table.put(header.get(counter), cad);
                counter++;
            }
        }
        return table;
    }
}
